import { App, ModalProps, Upload } from 'antd';
import { t } from 'i18next';
import { useEffect, useRef, useState } from 'react';

import externalSitesService from '@/api/services/externalSitesService';
import { Button } from '@/components/eai-design';
import { SvgIcon } from '@/components/icon';
import Modals from '@/components/modals/Modals';
import { useConfirm } from '@/hooks/use-confirm';

import type { RcFile } from 'rc-upload/lib/interface';

const { Dragger } = Upload;

interface ImportModalProps extends ModalProps {
  open: boolean;
  onCancel: () => void;
  onRefresh?: () => void;
}

const ImportModal = ({ open, onCancel, onRefresh }: ImportModalProps) => {
  const { message } = App.useApp();
  const [fileList, setFileList] = useState<RcFile[]>([]);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [isUploading, setIsUploading] = useState(false);
  const [maxRetries] = useState(20); // 最大重试次数，60秒超时
  const [retryInterval] = useState(3000); // 重试间隔，3秒
  const [taskId, setTaskId] = useState('');
  const abortImportRef = useRef<AbortController | null>(null);

  const { openConfirm, ConfirmModal } = useConfirm();

  const beforeUpload = (file: RcFile) => {
    if (file.size > 1 * 1024 * 1024) {
      message.error('文件大小不能超过 1MB');
      return Upload.LIST_IGNORE;
    }
    if (file.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
      message.error('只支持 xlsx 文件');
      return Upload.LIST_IGNORE;
    }
    return file;
  };

  const handleFileChange = (info: any) => {
    const { file, fileList } = info;

    // 处理文件删除的情况 - 当 fileList 为空时表示删除了文件
    if (fileList.length === 0) {
      setFileList([]);
      return;
    }

    // 处理新添加的文件
    if (file && file.uid) {
      // 验证文件
      const validationResult = beforeUpload(file);
      if (validationResult === Upload.LIST_IGNORE) {
        setFileList([]);
        return;
      }

      // 只保留最新的文件
      setFileList([file]);
    }
  };

  const resetUploadState = () => {
    setFileList([]);
    setUploadProgress(0);
    setIsUploading(false);
    setTaskId('');
    if (abortImportRef.current) {
      abortImportRef.current.abort();
      abortImportRef.current = null;
    }
  };

  const handleUploadComplete = (isSuccess: boolean, messageText: string) => {
    if (isSuccess) {
      message.success(messageText);
    } else {
      message.warning(messageText);
    }
    resetUploadState();
    onCancel();
    onRefresh?.();
  };

  const getProgress = async (
    task_id: string,
    signal: AbortSignal,
    retryCount = 0,
  ): Promise<void> => {
    console.log('getProgress', task_id, signal.aborted);
    if (signal.aborted) {
      console.log('getProgress', task_id, signal.aborted, '导入已取消');
      resetUploadState();
      return;
    }
    // 检查是否超过最大重试次数
    if (retryCount >= maxRetries) {
      message.error('导入任务超时，请稍后重试');
      resetUploadState();
      return;
    }

    try {
      const res = await externalSitesService.getExternalSitesImportProgress(task_id, signal);

      // 计算进度：上传占20%，处理占80%
      const progress = 20 + Math.round(res.progress * 0.8);
      setUploadProgress(progress);

      // 检查任务状态
      if (res.is_running === 1) {
        // 任务仍在运行，继续轮询
        setTimeout(() => {
          if (signal.aborted) {
            console.log('getProgress timeout', task_id, signal.aborted, '导入已取消');
            return;
          }
          getProgress(task_id, signal, retryCount + 1);
        }, retryInterval);
      } else {
        // 任务完成
        const isSuccess = res.progress === 100;
        handleUploadComplete(isSuccess, res.message || '导入完成');
      }
    } catch (error) {
      console.error('获取导入进度失败:', error);
      message.error('导入失败, 请尝试重新导入！');
      resetUploadState();
    }
  };

  const handleOk = async () => {
    if (fileList.length === 0) {
      message.error('请先选择文件');
      return;
    }

    setIsUploading(true);
    setUploadProgress(0);

    const formData = new FormData();
    formData.append('file', fileList[0]);

    try {
      const res = await externalSitesService.importExternalSites(formData, (progressEvent) => {
        if (progressEvent.progress) {
          const progress = Math.round(progressEvent.progress * 0.2);
          setUploadProgress(progress);
        }
      });

      // 开始轮询进度
      setTaskId(res.task_id);
      const controller = new AbortController();
      abortImportRef.current = controller;
      const { signal } = abortImportRef.current;
      getProgress(res.task_id, signal);
    } catch (error) {
      console.error('文件上传失败:', error);
      message.error('文件上传失败，请重试');
      resetUploadState();
    }
  };

  const handleCancel = () => {
    openConfirm(
      async () => {
        await externalSitesService.terminateExternalSitesImport(taskId);
        if (abortImportRef.current) {
          abortImportRef.current.abort();
          console.log('handleCancel: 已取消所有请求');
        }
        message.success('导入已取消');
        resetUploadState();
      },
      undefined,
      '确认取消导入？',
    )();
  };

  useEffect(() => {
    return () => {
      resetUploadState();
    };
  }, []);

  useEffect(() => {
    if (!open) {
      resetUploadState();
    }
  }, [open]);

  return (
    <Modals
      title={`导入${t('sys.menu.AINav')}`}
      destroyOnHidden
      open={open}
      onCancel={onCancel}
      onOk={handleOk}
      width={480}
      confirmLoading={isUploading}
    >
      <ul className="flex list-inside list-disc flex-col text-sm text-text-4">
        <li>
          根据 xlsx 模板整理要导入的名单。
          <a className="text-@brand-color" href="/openapi/v2/external-sites/import/template">
            下载 xlsx 模板
          </a>
        </li>
        <li>只支持 xlsx 文件。</li>
        <li>只支持上传一个文件，单个文件不超过1MB。</li>
        <li>相同地址会自动合并</li>
      </ul>
      {fileList.length === 0 ? (
        <Dragger
          listType="picture"
          maxCount={1}
          style={{
            border: 'none',
            backgroundColor: '#ECEFF8',
            marginTop: '16px',
            height: '94px',
            borderRadius: '8px',
          }}
          multiple={false}
          accept=".xlsx"
          beforeUpload={() => false} // 阻止自动上传
          onChange={handleFileChange}
          fileList={fileList}
        >
          <div className="flex h-full w-full flex-col items-center justify-center gap-2">
            <SvgIcon icon="icon-upload" size={28} style={{ color: '#545769' }} />
            <span>{fileList.length > 0 ? fileList[0].name : '上传 xlsx 文件'}</span>
          </div>
        </Dragger>
      ) : (
        <div className="relative mt-4 overflow-hidden rounded-lg bg-[#ECEFF8] px-4 py-8">
          {/* 进度条背景 */}
          <div
            className="absolute inset-0 transition-all duration-300 ease-out"
            style={{
              background: `linear-gradient(90deg, #1890ff ${uploadProgress}%, transparent ${uploadProgress}%)`,
              opacity: isUploading ? 0.3 : 0,
            }}
          />
          {/* 内容 */}
          <div className="relative flex h-full w-full items-center justify-between gap-2">
            <div className="flex items-center gap-2">
              <div>{fileList[0].name}</div>
              {isUploading && <span className="text-blue-600 text-sm">{uploadProgress}%</span>}
            </div>
            {uploadProgress > 0 && uploadProgress < 100 && (
              <Button danger type="link" onClick={handleCancel}>
                取消
              </Button>
            )}
            {!isUploading && (
              <Button danger type="link" onClick={() => setFileList([])}>
                删除
              </Button>
            )}
          </div>
        </div>
      )}
      <ConfirmModal />
    </Modals>
  );
};

export default ImportModal;
